import userCenterUpdatePasswordApi from '@/api/userCenter/userCenterUpdatePasswordApi'
import IUserCenterUpdatePasswordForm from '@/model/form/userCenter/IUserCenterUpdatePasswordForm'
import { useAppSelector } from '@/store'
import { onModalCancel, ToastError, ToastSuccess } from '@/util/CommonUtil'
import { logout, passwordRSAEncrypt, RSAEncryptPro } from '@/util/UserUtil'
import Validator from '@/util/Validator'
import { Form, Modal } from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useRef, useState } from 'react'

interface IUpdatePassword {
  modalVisible: boolean
  setModalVisible: Dispatch<SetStateAction<boolean>>
}

export default function UpdatePassword(props: IUpdatePassword) {
  const formApi = useRef<FormApi>()
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态
  const rsaPublicKey = useAppSelector((state) => state.common.rsaPublicKey)

  return (
    <Modal
      title="修改密码"
      visible={props.modalVisible}
      onOk={() => {
        formApi.current?.submitForm()
      }}
      onCancel={() => {
        onModalCancel(props.setModalVisible, formApi.current, {})
      }}
      maskClosable={false}
      confirmLoading={confirmLoading}
    >
      <Form
        onSubmit={(form) => {
          if (confirmLoading) return
          modalSubmitClick(
            form as IUserCenterUpdatePasswordForm,
            setConfirmLoading,
            rsaPublicKey,
            props.setModalVisible
          )
        }}
        getFormApi={(api) => (formApi.current = api)}
        disabled={confirmLoading}
      >
        <Form.Input
          label={{ text: '旧密码', required: true }}
          field="oldPassword"
          validate={Validator['passwordValidate']}
          showClear
          mode="password"
        />
        <Form.Input
          label={{ text: '新密码', required: true }}
          field="newPassword"
          validate={Validator['passwordValidate']}
          showClear
          mode="password"
        />
      </Form>
    </Modal>
  )
}

// 表单提交
function modalSubmitClick(
  form: IUserCenterUpdatePasswordForm,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  rsaPublicKey: string,
  setModalVisible: Dispatch<SetStateAction<boolean>>
) {
  if (form.oldPassword === form.newPassword) {
    return ToastError('新旧密码不能一样，请重新输入 (ノ￣▽￣)')
  }

  setConfirmLoading(true)

  const date = new Date()
  form.newOrigPassword = RSAEncryptPro(form.newPassword, rsaPublicKey, date)
  form.newPassword = passwordRSAEncrypt(form.newPassword, rsaPublicKey, date)
  form.oldPassword = passwordRSAEncrypt(form.oldPassword, rsaPublicKey, date)

  userCenterUpdatePasswordApi(form)
    .then(({ data }) => {
      ToastSuccess(data.msg)
      setConfirmLoading(false)
      setModalVisible(false)
      logout()
    })
    .catch(() => {
      setConfirmLoading(false)
    })
}
